package com.bosssoft.hr.jobmonitor.core.Timer;

import com.bosssoft.hr.jobmonitor.config.common.SysConfig;
import com.bosssoft.hr.jobmonitor.core.file.FileTool;
import com.bosssoft.hr.jobmonitor.entity.Task;
import com.bosssoft.hr.jobmonitor.entity.User;
import com.bosssoft.hr.jobmonitor.util.DateUtil;
import com.bosssoft.hr.jobmonitor.util.XmlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/***
 * @Author lys(cherish)
 * @Description 文件检查工具
 * @Date  2019/2/26
 **/
@Component
public class CheckFileTaskTool {

    //文件处理工具注入
    @Autowired
    private FileTool fileTool;

    /***
     * @Author lys(cherish)
     * @Description 查询所有的用户
     * @Date  2019/2/26
     * @Param []
     * @return java.util.List<com.bosssoft.hr.jobmonitor.entity.User>
     **/
    public List<User> queryAllUser(){
        String xmlStr = fileTool.readFile("resource"+File.separator+"user"+File.separator+"allUser.xml");
        List<User> userList = XmlUtil.toBean(xmlStr, List.class);
        return userList;
    }

    /***
     * @Author lys(cherish)
     * @Description 查询任务未提交用户列表
     * @Date  2019/2/26
     * @Param [task] 任务
     * @return java.util.List<com.bosssoft.hr.jobmonitor.entity.User>
     **/
    public List<User> checkNoSubmit(Task task){
        SysConfig sysconfig = fileTool.getSysConfig();
        String begintimeStr = task.getRemind().getBegintime();
        Date date = DateUtil.fmtStr2Date(begintimeStr);
        String todayDir = DateUtil.getTodayDir(date);
        File file = new File(sysconfig.getHomeDir() + File.separator + todayDir);
        List<String> filenameList = new ArrayList<>();
        if(file.exists()){
            String[] filenames = file.list();
            for (String f:filenames) {
                filenameList.add(f);
            }
        }
        List<User> allUser = queryAllUser();
        List<User> notSubmitList = check(allUser, filenameList);
        return notSubmitList;
    }

    /***
     * @Author lys(cherish)
     * @Description 所有用户减去提交任务的用户，供 checkNoSubmit 方法调用
     * @Date  2019/2/26
     * @Param [allUser, submitNameList]
     * @return java.util.List<com.bosssoft.hr.jobmonitor.entity.User>
     **/
    public List<User>  check(List<User> allUser, List<String> submitNameList){
        ArrayList<User> notSubmitList = new ArrayList<>();
        for(User user:allUser){
            if(!submitNameList.contains(user.getName())){
                notSubmitList.add(user);
            }
        }
       return notSubmitList;
    }

}
